<template>
  <div class="activity-card" @click="goToDetail">
    <!-- 动态卡片头部区域 -->
    <div class="activity-header">
      <!-- 用户头像 -->
      <img class="avatar" :src="userInfo.avatar"  @click.stop="goToUserProfile" style="cursor: pointer;" />
      <!-- 用户昵称 -->
      <span class="nickname"  @click.stop="goToUserProfile" style="cursor: pointer;">{{ userInfo.nickname }}</span>
      <!-- 时间显示 -->
      <span class="activity-time">{{ formatActivityTime(activity.createDate || activity.updateDate) }}</span>
    </div>

    <!-- 动态主体内容区 -->
    <div class="activity-main">
      <div class="activity-content-block">
        <!-- 显示话题标签 -->
        <div v-if="topicContent" class="activity-topic" @click.stop="searchTopic(topicContent)">
          <span class="topic-hash">#</span>
          <span class="topic-text">{{ topicContent }}</span>
        </div>
        <!-- 渲染格式化后的动态正文内容 -->
        <div class="activity-content" v-html="formatContent(activity.content)"></div>
      </div>
    </div>

    <!-- 媒体资源展示区域 -->
    <div class="activity-images" v-if="activity.mediaUrls && parseImages(activity.mediaUrls).length">
      <template v-for="(media, idx) in parseImages(activity.mediaUrls)">
        <!-- 图片类型媒体 -->
        <img
            v-if="/\.(jpg|jpeg|png|gif|webp)$/i.test(media)"
            :key="'img'+idx"
            :src="media"
            class="activity-img"
            @click.stop="onImgClick(idx)"
        />
        <!-- 视频类型媒体 -->
        <video
            v-else
            :key="'video'+idx"
            :src="media"
            class="activity-img"
            @click.stop="onImgClick(idx)"
            muted
            preload="metadata"
            playsinline
        ></video>
      </template>
    </div>

    <!-- 底部互动功能按钮 -->
    <div class="activity-actions">
      <!-- 评论按钮 -->
      <span class="action-group comment-action" @click="$emit('view-comments')">
        <i class="fas fa-comment"></i>
        <img width="24" height="24" class="action-icon" src="https://img.icons8.com/windows/32/chat-message.png" alt="chat-message"/>
        <span class="action-num">{{ activity.commentNum || 0 }}</span>
      </span>
      <!-- 点赞按钮 -->
      <span class="action-group like-action"  @click.stop="$emit('like', activity)">
        <i class="fas fa-thumbs-up"></i>
        <img width="24" height="24" class=".action-icon" src="https://img.icons8.com/material-outlined/24/facebook-like--v1.png" alt="facebook-like--v1"/>
        <span class="action-num">{{ activity.likesCount || 0 }}</span>
      </span>
    </div>

    <div v-if="showActions" class="action-btns-bottom-left">
  <span class="action-group edit-action" @click.stop="onEdit">
    <i class="fas fa-edit"></i>
    <span class="action-num">修改</span>
  </span>
      <span class="action-group delete-action" @click.stop="onDelete">
    <i class="fas fa-trash"></i>
    <span class="action-num">删除</span>
  </span>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, watch } from 'vue';
import axios from 'axios';
import { useRouter } from 'vue-router';


/**
 * 定义组件接收的属性
 * @property {Object} activity - 当前动态对象，必须传入
 * @property {Boolean} [showActions=false] - 是否显示操作按钮（如编辑、删除）
 */
const props = defineProps({
  activity: { type: Object, required: true },
  showActions: { type: Boolean, default: false }
});
const defaultAvatar = 'https://example.com/avatars/guest1.jpg';

/**
 * 存储当前动态发布者的信息
 * 默认为匿名用户信息
 */
const userInfo = ref({
  nickname: '匿名用户',
  avatar: defaultAvatar
});

/**
 * 组件挂载时加载用户信息
 * 根据动态中的 userId 请求对应的用户数据并更新 userInfo
 */
onMounted(async () => {
  if (props.activity.userId) {
    try {
      const res = await axios.get(`http://localhost:8084/api/user/${props.activity.userId}`);
      userInfo.value.nickname = res.data.nickname || '匿名用户';
      userInfo.value.avatar = res.data.avatar || defaultAvatar;
    } catch (error) {
      console.error('Failed to fetch user info:', error);
    }
  }
});

/**
 * 定义自定义事件发射器
 * 可触发 view-media、deleted 和 edit 三个事件
 */
const emit = defineEmits(['view-media', 'deleted', 'edit']);

/**
 * 处理图片或视频点击事件
 * 将解析出的所有媒体链接传递给父组件用于预览
 * @param {Number} idx - 被点击的媒体索引
 */
function onImgClick(idx) {
  const images = parseImages(props.activity.mediaUrls).map(media => {
    if (typeof media === 'string') return media;
    if (media && media.url) return media.url;
    return '';
  });
  emit('view-media', images, idx);
}

/**
 * 解析媒体 URL 字符串或数组为统一结构
 * 支持字符串数组或 JSON 字符串形式的数据
 * @param {String|Array} mediaUrls - 原始媒体地址列表
 * @returns {Array<String>} - 返回处理后的一维字符串数组
 */
function parseImages(mediaUrls) {
  if (!mediaUrls) return [];
  try {
    const arr = Array.isArray(mediaUrls) ? mediaUrls : JSON.parse(mediaUrls);
    return arr.map(item => (typeof item === 'string' ? item : (item.url || '')));
  } catch {
    return [];
  }
}

/**
 * 存储从接口获取到的话题内容
 */
const topicContent = ref('');

/**
 * 获取与当前动态关联的话题内容
 * 若请求成功则设置 topicContent 的值
 */
async function fetchTopicContent() {
  if (!props.activity.id) return;
  try {
    const response = await axios.get(`http://localhost:8085/activity/${props.activity.id}/topic`);
    topicContent.value = response.data.content || '';
  } catch {
    topicContent.value = '';
  }
}

/**
 * 初始化加载话题内容，并监听 activity.id 变更重新拉取
 */
onMounted(fetchTopicContent);
watch(() => props.activity.id, fetchTopicContent);

/**
 * 删除当前动态
 * 弹窗确认后发起 DELETE 请求，若成功通知父组件移除该条目
 */
async function onDelete() {
  if (!confirm('确定要删除这条动态吗？')) return;
  try {
    // 先获取动态详情，检查是否有话题
    const activityDetail = await axios.get(`http://localhost:8085/activity/${props.activity.id}`);

    // 删除动态
    await axios.delete(`http://localhost:8085/activity/${props.activity.id}`);

    // 如果动态有关联话题，减少话题计数
    if (activityDetail.data.topicId) {
      try {
        await axios.post(`http://localhost:8085/topics/${activityDetail.data.topicId}/decrement`);
      } catch (e) {
        console.error('减少话题计数失败:', e);
      }
    }

    emit('deleted', props.activity.id);
  } catch (e) {
    alert('删除失败');
  }
}

/**
 * 编辑当前动态
 * 向父组件发送 edit 事件携带 activity 数据
 */
function onEdit() {
  emit('edit', props.activity);
}

/**
 * 对动态文本内容进行换行符替换处理
 * 将 \n 或 \r\n 替换为 HTML 中的 <br/> 标签以支持换行显示
 * @param {String} content - 待处理的内容文本
 * @returns {String} - 处理后的 HTML 内容
 */
function formatContent(content) {
  if (!content) return '';
  return content.replace(/\r\n/g, '<br/>').replace(/\n/g, '<br/>');
}

/**
 * 格式化活动时间显示
 * @param {String} timeStr - 时间字符串
 * @returns {String} 格式化后的时间显示
 */
function formatActivityTime(timeStr) {
  if (!timeStr) return '未知时间';

  try {
    const date = new Date(timeStr);
    if (isNaN(date.getTime())) {
      return '未知时间';
    }

    const now = new Date();
    const diffMs = now - date;
    const diffMinutes = Math.floor(diffMs / 60000);
    const diffHours = Math.floor(diffMs / 3600000);
    const diffDays = Math.floor(diffMs / 86400000);

    if (diffMinutes < 1) {
      return '刚刚';
    } else if (diffMinutes < 60) {
      return `${diffMinutes}分钟前`;
    } else if (diffHours < 24) {
      return `${diffHours}小时前`;
    } else if (diffDays < 7) {
      return `${diffDays}天前`;
    } else {
      // 超过7天显示具体日期
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      return `${year}-${month}-${day}`;
    }
  } catch (error) {
    console.error('时间格式化错误:', error);
    return '未知时间';
  }
}

const router = useRouter();

function goToDetail() {
  router.push({
    name: 'ActivityDetail',
    params: { id: props.activity.id }
  });
}
// 跳转到用户主页
function goToUserProfile() {
  if (props.activity.userId) {
    router.push(`/user/${props.activity.userId}`);
  }
}
function searchTopic(keyword) {
  // 使用事件总线通知 TopBarSearch 组件填充搜索框
  window.dispatchEvent(new CustomEvent('fill-search-input', {
    detail: { keyword }
  }));

  // 确保跳转到搜索页面
  setTimeout(() => {
    router.push({
      path: '/search',
      query: { q: keyword, type: 'topic' }
    });
  }, 100);
}
</script>


<style scoped>
.activity-card {
  background: #fff;
  border-radius: 18px;
  box-shadow: 0 2px 12px rgba(44,62,80,0.08);
  margin-bottom: 32px;
  padding: 36px 48px 28px 48px;
  width: 100%;
  margin-left: auto;
  margin-right: auto;
  display: flex;
  flex-direction: column;
  gap: 12px;
  min-height: 220px;
  position: relative;
}
.activity-header {
  display: flex;
  align-items: center;
  margin-bottom: 12px;
  padding-left: 8px;
  margin-top: 8px;
}
.avatar {
  width: 38px;
  height: 38px;
  border-radius: 50%;
  margin-right: 10px;
}
.nickname {
  font-weight: bold;
  color: #23232b;
}
.activity-time {
  flex: 1;
  text-align: right;
  color: #888;
  font-size: 14px;
  margin-right: 80px;
  min-width: 80px; /* 确保有足够的空间 */
  white-space: nowrap; /* 防止换行 */
}
.activity-main {
  display: flex;
  gap: 24px;
  align-items: flex-start;
  padding-left: 8px;
  padding-right: 8px;
}
.activity-content-block {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: center;
  gap: 8px;
  padding-left: 4px;
}
.activity-content {
  color: #444;
  font-size: 15px;
  text-align: left;
  white-space: pre-wrap;
}
.activity-images {
  display: flex;
  flex-wrap: wrap;
  gap: 18px;
  margin-top: 12px;
  margin-bottom: 0;
  max-width: 100%;
  justify-content: flex-start;
  position: static;
  padding: 0 12px 8px 12px;
  box-sizing: border-box;
}
.activity-img {
  flex: 0 0 calc((100% - 48px) / 4);
  min-width: 0;
  width: calc((100% - 48px) / 4);
  max-width: calc((100% - 48px) / 4);
  height: calc((100% - 48px) / 4);
  aspect-ratio: 1 / 1;
  object-fit: cover;
  border-radius: 14px;
  background: #f0f0f0;
  box-shadow: 0 1px 4px rgba(44,62,80,0.08);
  display: block;
  cursor: pointer;
  transition: transform 0.2s ease, box-shadow 0.2s ease;
}
@media (max-width: 900px) {
  .activity-img {
    width: calc((100% - 18px) / 2);
    max-width: calc((100% - 18px) / 2);
    height: calc((100% - 18px) / 2);
  }
}
.activity-img:hover {
  transform: scale(1.02);
  box-shadow: 0 4px 12px rgba(44, 62, 80, 0.15);
}
.activity-actions {
  display: flex;
  gap: 32px;
  align-items: center;
  justify-content: flex-end;
  margin-top: 18px;
  padding-bottom: 2px;
  padding-right: 8px;
}
.action-group {
  display: flex;
  align-items: center;
  font-size: 18px;
  gap: 6px;
  user-select: none;
  border: 1.5px solid currentColor;
  border-radius: 18px;
  padding: 4px 18px 4px 12px;
  background: #fff;
  transition: border-color 0.2s, box-shadow 0.2s;
  cursor: pointer;
  min-width: 56px;
  justify-content: center;
  position: relative;
}
.comment-action {
  color: #bfc3c9;
}
.comment-action:hover {
  border-color: #555;
  box-shadow: 0 2px 8px rgba(44,62,80,0.10);
}
.comment-action .action-num {
  margin-left: 2px;
  font-size: 16px;
  color: inherit;
  position: static;
}
.like-action {
  color: #bfc3c9;
}
.like-action:hover {
  border-color: #555;
  box-shadow: 0 2px 8px rgba(44,62,80,0.10);
}
.like-action .action-num {
  margin-left: 2px;
  font-size: 16px;
}

.action-icon {
  width: 20px;
  height: 20px;
  margin-right: 4px;
  vertical-align: middle;
}
.modal-overlay {
  overflow: auto;
  /* 或 overflow-y: auto; */
}
.modal-content {
  max-width: 520px;
  width: 95vw;
  max-height: 90vh;
  overflow: visible;
  margin: 0 auto;
  border-radius: 16px;
  /* 其它样式 */
}
.activity-post-editor {
  width: 100%;
  max-width: 100%;
  box-sizing: border-box;
  overflow: visible;
  height: auto;
  max-height: none;
}
.row-flex {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-bottom: 18px;
}

.visibility-selector {
  flex: 1;
  margin-bottom: 0;
  position: relative;
  min-width: 140px;
  max-width: 180px;
}

.selected-visibility {
  min-width: 140px;
  max-width: 180px;
  width: 100%;
  box-sizing: border-box;
  border: 1.5px solid #23232b;
  border-radius: 12px;
  padding: 10px 18px;
  background: #f8f9fa;
  color: #23232b;
  display: flex;
  align-items: center;
  cursor: pointer;
  font-size: 16px;
  margin-bottom: 0;
  transition: border 0.2s, background 0.2s;
}

.selected-visibility:hover {
  border: 1.5px solid #3498db;
  background: #eaf6fd;
}

.visibility-menu {
  min-width: 140px;
  max-width: 180px;
  right: auto;
  left: 0;
  width: 100%;
  box-sizing: border-box;
  position: absolute;
  border: 1.5px solid #23232b;
  border-radius: 12px;
  background: #fff;
  margin-top: 4px;
  box-shadow: 0 2px 8px rgba(44,62,80,0.10);
  overflow: hidden;
  z-index: 10;
}

.visibility-option {
  color: #23232b !important;
  padding: 12px 18px;
  cursor: pointer;
  border-radius: 0;
  font-size: 16px;
  transition: background 0.2s, color 0.2s;
  text-align: left;
  background: #fff;
}

.visibility-option.active, .visibility-option:hover {
  color: #3498db !important;
  background: #eaf6fd;
  font-weight: bold;
}

.media-upload-inline {
  flex-shrink: 0;
  display: flex;
  align-items: center;
  height: 44px;
}

.small-upload-btn {
  min-width: 120px;
  max-width: 140px;
  padding: 10px 0;
  font-size: 15px;
  border-radius: 12px;
  margin-bottom: 0;
  box-shadow: 0 2px 8px rgba(52,152,219,0.10);
  height: 44px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.activity-topic {
  display: inline-flex;
  align-items: center;
  background: none;
  color: #3498db;
  font-size: 18px;
  font-weight: 600;
  border-radius: 6px;
  padding: 1px 8px 1px 6px;
  margin-bottom: 6px;
  margin-right: 6px;
  cursor: pointer;
  transition: color 0.2s;
  border: none;
  user-select: none;
  max-width: 25%;
  min-width: 0;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.activity-topic:hover {
  color: #1769aa;
  background: none;
}

.topic-hash {
  font-size: 18px;
  font-weight: 600;
  margin-right: 2px;
  color: #3498db;
}

.topic-text {
  color: inherit;
  font-size: 18px;
  font-weight: 600;
}

.edit-action {
  color: #2196f3;
}
.edit-action:hover {
  border-color: #2196f3;
  background: #eaf6ff;
}
.delete-action {
  color: #e74c3c;
}
.delete-action:hover {
  border-color: #e74c3c;
  background: #fff0f0;
}
.action-btns {
  position: absolute;
  top: 18px;
  right: 24px;
  display: flex;
  gap: 10px;
  z-index: 2;
}
.edit-btn, .delete-btn {
  border: none;
  outline: none;
  border-radius: 16px;
  padding: 4px 14px;
  font-size: 14px;
  font-weight: 500;
  cursor: pointer;
  background: #f7faff;
  color: #2196f3;
  transition: background 0.2s, color 0.2s;
  box-shadow: 0 1px 4px rgba(44,62,80,0.08);
  display: flex;
  align-items: center;
  gap: 4px;
}
.delete-btn {
  color: #e74c3c;
}
.edit-btn:hover {
  background: #eaf6ff;
  color: #1565c0;
}
.delete-btn:hover {
  background: #fff0f0;
  color: #b71c1c;
}

/* 新增样式：操作按钮底部定位 */
.action-btns-bottom {
  position: absolute;
  bottom: 16px;
  right: 16px;
  display: flex;
  gap: 8px;
  z-index: 2;
}

.action-btns-bottom button {
  padding: 4px 12px;
  font-size: 14px;
  border: none;
  border-radius: 12px;
  cursor: pointer;
  transition: background 0.2s, color 0.2s;
  display: flex;
  align-items: center;
  gap: 4px;
}

.edit-btn {
  background: #f7faff;
  color: #2196f3;
  border: 1px solid #d1e3ff;
}

.edit-btn:hover {
  background: #eaf6ff;
  color: #1565c0;
  border: 1px solid #b3d9ff;
}

.delete-btn {
  background: #fff0f0;
  color: #e74c3c;
  border: 1px solid #ffeaea;
}

.delete-btn:hover {
  background: #ffebec;
  color: #b71c1c;
  border: 1px solid #ffcccc;
}
/* 新增样式：操作按钮左下角定位 */
.action-btns-bottom-left {
  position: absolute;
  bottom: 16px;
  left: 16px;
  display: flex;
  gap: 8px;
  z-index: 2;
}

/* 使用与点赞按钮相同的样式 */
.edit-action, .delete-action {
  display: flex;
  align-items: center;
  font-size: 18px;
  gap: 6px;
  user-select: none;
  border: 1.5px solid currentColor;
  border-radius: 18px;
  padding: 4px 18px 4px 12px;
  background: #fff;
  transition: border-color 0.2s, box-shadow 0.2s;
  cursor: pointer;
  min-width: 56px;
  justify-content: center;
  color: #bfc3c9;
}

.edit-action:hover {
  border-color: #555;
  box-shadow: 0 2px 8px rgba(44,62,80,0.10);
  color: #2196f3;
}

.delete-action:hover {
  border-color: #555;
  box-shadow: 0 2px 8px rgba(44,62,80,0.10);
  color: #e74c3c;
}

.action-num {
  margin-left: 2px;
  font-size: 16px;
  color: inherit;
}

</style>